import auth from '../auth'
import appConfig from '../config'
import request from 'superagent'
import Q from 'q'
import {getErrorMsg} from 'utils/http'

exports.uploadFile = function (data, progressCallback) {
  let deferred = Q.defer();
  const req = request.post(appConfig.apiHost + '/File')
  req.set('Authorization',auth.getToken() ? `HAuth ${auth.getToken()}` : '')
  req.attach(data.name ? data.name : 'file',data)
  if(progressCallback){
    req.on('progress', progressCallback)
  }
  req.end((err,res)=>{
    console.log(res)
    if(res && res.statusCode === 200){
      if(res.body){
        if(res.body.State >= 0){
          deferred.resolve(res.body);
        }else{
          deferred.reject({
            code: res.body.State ,
            msg: getErrorMsg(res.body.State)
          });
        }
      }else {
        deferred.reject({
          code: 666,
          msg: 'response body error'
        });
      }
    }else{
      deferred.reject({
        code: res.statusCode,
        msg: getErrorMsg(res.statusCode)
      });
    }
  })
  return {
    request: req,
    promise: deferred.promise
  }
}
